package com.sikaryofficial.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sikaryofficial.common.core.utils.ServletUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.gateway.config.properties.CaptchaProperties;
import com.sikaryofficial.gateway.config.properties.EmailIgnoreWhiteProperties;
import com.sikaryofficial.gateway.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * H5 邮箱验证码过滤器
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class H5ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] { "/auth/h5Login", "/auth/h5Register", "/auth/channel/customers/login", "/auth/channel/customers/register" };

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CaptchaProperties captchaProperties;

    private static final String EMAIL_ADDRESS = "emailAddress";

    private static final String CAPTCHA_CODE = "captchaCode";

    @Value("${hismk.gateway.captchaValid}")
    private boolean captchaValid;
    @Resource
    private EmailIgnoreWhiteProperties emailIgnoreWhiteProperties;

    @Override
    public GatewayFilter apply(Object config)
    {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            // 验证码关闭，不处理
            if(Boolean.FALSE.equals(captchaValid)){
                log.info("邮箱验证码校验关闭，不处理");
                return chain.filter(exchange);
            }
            // 非登录/注册请求或验证码关闭，不处理
            if (!StringUtils.containsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) || !captchaProperties.getEnabled())
            {
                return chain.filter(exchange);
            }
            // TODO： 其他逻辑，要在下面进行追加
            if (whiteEmailsProcess(request)) {
                return chain.filter(exchange);
            }
            try
            {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSON.parseObject(rspStr);
                log.info("H5ValidateCodeFilter rspStr:{}",rspStr);
                validateCodeService.checkEmailCaptcha(obj.getString(EMAIL_ADDRESS), obj.getString(CAPTCHA_CODE));
            }
            catch (Exception e)
            {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }

    /**
     * 白名单邮箱处理
     * @param request
     * @return
     */
    private boolean whiteEmailsProcess(ServerHttpRequest request) {
        String rspStr1 = resolveBodyFromRequest(request);
        JSONObject obj1 = JSON.parseObject(rspStr1);
        List<String> whiteEmails = emailIgnoreWhiteProperties.getWhites();
        if(CollUtil.isNotEmpty(whiteEmails) && whiteEmails.contains(obj1.getString(EMAIL_ADDRESS))){
            log.info("白名单邮箱-关闭验证码校验，不处理");
            return true;
        }
        return false;
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
